package fr.obsmip.sedoo.client.misc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;

import fr.obsmip.sedoo.client.PortailRBV;
import fr.obsmip.sedoo.client.event.ActionEventConstant;
import fr.obsmip.sedoo.client.service.GeonetworkObservatoryService;
import fr.obsmip.sedoo.client.service.GeonetworkObservatoryServiceAsync;
import fr.obsmip.sedoo.shared.api.IsObservatory;
import fr.obsmip.sedoo.shared.domain.GeonetworkObservatoryDTO;
import fr.obsmip.sedoo.shared.util.IsObservatoryComparator;
import fr.sedoo.commons.client.callback.LoadCallBack;
import fr.sedoo.commons.client.event.ActionStartEvent;
import fr.sedoo.commons.client.message.CommonMessages;
import fr.sedoo.commons.client.service.DefaultAbstractCallBack;

public class ClientObservatoryList {

	private static ArrayList<IsObservatory> observatories = new ArrayList<IsObservatory>();
	private static boolean loaded=false;
	private static ArrayList<LoadCallBack<ArrayList<IsObservatory>>> callBacks = new ArrayList<LoadCallBack<ArrayList<IsObservatory>>>();
	public final static GeonetworkObservatoryServiceAsync GEONETWORK_OBSERVATORY_SERVICE = GWT.create(GeonetworkObservatoryService.class);	

	public static void getObservatories(LoadCallBack<ArrayList<IsObservatory>> callBack) {
		if (loaded)
		{
			ArrayList<IsObservatory> clone = new ArrayList<IsObservatory>();
			clone.addAll(observatories);
			callBack.postLoadProcess(clone);
		}
		else
		{
			callBacks.add(callBack);
			loadObservatories();
		}
	}

	private static void loadObservatories()
	{
		final EventBus eventBus = PortailRBV.getClientFactory().getEventBus();
		ActionStartEvent e = new ActionStartEvent(CommonMessages.INSTANCE.loading(), ActionEventConstant.OBSERVATORIES_LOADING_EVENT, true);
		eventBus.fireEvent(e);

		GEONETWORK_OBSERVATORY_SERVICE.findAll(new DefaultAbstractCallBack<ArrayList<GeonetworkObservatoryDTO>>(e, eventBus) {

			@Override
			public void onSuccess(ArrayList<GeonetworkObservatoryDTO> result) {
				super.onSuccess(result);
				observatories = new ArrayList<IsObservatory>();
				observatories.addAll(result);
				Collections.sort(observatories, new IsObservatoryComparator());
				loaded=true;
				Iterator<LoadCallBack<ArrayList<IsObservatory>>> iterator = callBacks.iterator();
				while (iterator.hasNext()) {
					getObservatories(iterator.next());
				}
				callBacks.clear();
			}

		});
	}

	public static void updateObservatories()
	{
		loaded=false;
		loadObservatories();
	}
	
}
